package io;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class IOReceiver {
	private static final int BUF_SIZE = 256 * 1024 - 1;
	private static final int FILE_SIZE = 104857600;

	public static void main(String[] args) throws IOException {
		ServerSocket serverSocket = null;

		try {
			serverSocket = new ServerSocket(7777);
		} catch (IOException e) {
			System.err.println("Could not listen on port: 7777.");
			System.exit(1);
		}

		Socket clientSocket = null;
		System.out.println("Waiting for connection...");

		try {
			clientSocket = serverSocket.accept();
		} catch (IOException e) {
			System.err.println("Accept failed.");
			System.exit(1);
		}

		System.out.println("Connection successful");
		System.out.println("Waiting for input.....");

		InputStream in = clientSocket.getInputStream();

		byte[] buf = new byte[BUF_SIZE];

		int size = BUF_SIZE + 1;

		DataOutputStream dos = new DataOutputStream(new FileOutputStream(
				new File("data/net_rcv.bin")));

		int totalRcvd = 0;
		
		while (size > 0 && totalRcvd < FILE_SIZE) {
			size = in.read(buf);
			totalRcvd += size;
			System.out.println(size);
			if (size > 0) {
				dos.write(buf, 0, size);
			}
		}

		System.out.println("TX ack sent.");
		OutputStream socketOut = clientSocket.getOutputStream();
		socketOut.write(77);
		socketOut.close();

		dos.close();
		in.close();

		clientSocket.close();
		serverSocket.close();
	}
}
